﻿using CSRedis;
using DispatchDownloadVideo.Dto;
using Newtonsoft.Json;
using QskjLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DispatchDownloadVideo.Service
{
    public static class DownloadUpdate
    {
        /// <summary>
        /// 下载记录查询-启动下载-刷新进度
        /// </summary>
        public static void GetVideoData()
        {
            try
            {
                List<DownloadVideoFileDto> list = new List<DownloadVideoFileDto>();
                string dtS = DateTime.Now.ToString("yyyy-MM-dd"), dte = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                string sql = $@"select Id,userName,licensePlate,channel,deviceId,url,status,schedule,createtimedts,createtimedte,createtimeFiledts,createtimeFiledte,createtime,downloadType,fileSize,operateType,remarks,playId,ftpurl
                                from y_stream_download_video_file
                                where createtime>='{dtS}' and createtime<'{dte}' and status < 3";
                DataTable dt = MySqlHelper.GetDataTable(System.Data.CommandType.Text, sql);
                foreach (DataRow row in dt.Rows)
                {
                    DownloadVideoFileDto dvf = new DownloadVideoFileDto();
                    dvf.Id = Convert.ToInt32(row["Id"]);
                    dvf.userName = row["userName"] == DBNull.Value ? "" : row["userName"].ToString();
                    dvf.licensePlate = row["licensePlate"] == DBNull.Value ? "" : row["licensePlate"].ToString();
                    dvf.channel = row["channel"] == DBNull.Value ? "" : row["channel"].ToString();
                    dvf.deviceId = row["deviceId"] == DBNull.Value ? "" : row["deviceId"].ToString();
                    dvf.createtimeFiledts = Convert.ToDateTime(row["createtimeFiledts"]).ToString("yyyy-MM-ddTHH:mm:ss");
                    dvf.createtimeFiledte = Convert.ToDateTime(row["createtimeFiledte"]).ToString("yyyy-MM-ddTHH:mm:ss");
                    dvf.url = row["url"] == DBNull.Value ? "" : row["url"].ToString();
                    dvf.ftpurl = row["ftpurl"] == DBNull.Value ? "" : row["ftpurl"].ToString();
                    dvf.fileSize = row["fileSize"] == DBNull.Value ? "" : row["fileSize"].ToString();
                    dvf.status = row["status"] == DBNull.Value ? "" : row["status"].ToString();
                    dvf.remarks = row["remarks"] == DBNull.Value ? "" : row["remarks"].ToString();
                    dvf.playId = row["playId"] == DBNull.Value ? "" : row["playId"].ToString();
                    list.Add(dvf);
                    if (dvf.status == "1" || string.IsNullOrEmpty(dvf.url) || string.IsNullOrEmpty(dvf.playId))
                    {
                        if (string.IsNullOrWhiteSpace(dvf.ftpurl))
                        {
                            //DownloadVideoData(dvf);
                        }
                        else
                        {
                            DownloadVideoDataByFtp(dvf);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("下载记录查询信息异常" + JsonConvert.SerializeObject(e));
            }
        }
        /// <summary>
        /// 启动下载
        /// </summary>
        public static void DownloadVideoDataByFtp(DownloadVideoFileDto dvf)
        {
            try
            {
                CSRedisClient cSRedisClient = RedisHelp.GetInstanceSaas2();
                string ftpUrlInfo = cSRedisClient.Get("urlInfo:ftpUrlInfo");
                PlayUrlToken videoUrlDto = new PlayUrlToken();
                if ( string.IsNullOrEmpty(ftpUrlInfo))
                {
                    List<S_SystemUrl> systemUrls = new List<S_SystemUrl>();
                    string sqlUrl = $@"select name,keyname,url,groupname from S_SystemUrl";
                    DataTable dtUrl = MySqlHelper.GetDataTable(CommandType.Text, sqlUrl);
                    foreach (DataRow dr in dtUrl.Rows)
                    {
                        S_SystemUrl s = new S_SystemUrl();
                        s.Name = dr["name"].ToString();
                        s.KeyName = dr["keyname"].ToString();
                        s.Url = dr["url"].ToString();
                        s.GroupName = dr["groupname"].ToString();
                        systemUrls.Add(s);
                    } 
                    S_SystemUrl? ftpInfo = systemUrls.FirstOrDefault(p => p.KeyName == "videoHisDownload");
                    ftpUrlInfo = ftpInfo.Url;
                    cSRedisClient.Set("urlInfo:ftpUrlInfo", ftpInfo.Url, 1 * 60 * 60 * 10);//十小时过期
                }
                string[] ftpInfoArr = ftpUrlInfo.Split(';');
                string[] fileInfo = dvf.ftpurl.Split('/');
                string localFilePath = AppDomain.CurrentDomain.BaseDirectory + "videoFile_" + fileInfo.LastOrDefault();//文件本地地址
                Console.WriteLine(localFilePath); 
                string username = ftpInfoArr[2];
                string password = ftpInfoArr[3];
                //string[] filetype = localFilePath.Split('.');
                //string filetype1 = filetype.LastOrDefault();
                //string filename1 = fileInfo.LastOrDefault();
                string strKey = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Ticks;
                #region Ftp文件下载文件上传
                if (string.IsNullOrWhiteSpace(dvf.playId))
                {
                    #region ftp文件下载到本地
                    if (!File.Exists(localFilePath))
                    {
                        try
                        {
                            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dvf.ftpurl);
                            request.Method = WebRequestMethods.Ftp.DownloadFile;
                            request.Credentials = new NetworkCredential(username, password);

                            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                            Stream responseStream = response.GetResponseStream();
                            if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                            {
                                Console.WriteLine("FTP文件还不存在");
                                return;
                            }
                            string sqlUpdateKey = $@"update y_stream_download_video_file set playId='{strKey}',status=2,description='ftpsuccess' where id={dvf.Id}";
                            MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdateKey);

                            FileStream localFileStream = new FileStream(localFilePath, FileMode.Create);
                            byte[] buffer = new byte[1024 * 10 * 10];
                            int bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                            // Write the downloaded data to a local file.
                            while (bytesRead > 0)
                            {
                                localFileStream.Write(buffer, 0, bytesRead);
                                bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                            }
                            // Close the response and stream objects
                            response.Close();
                            localFileStream.Close();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("saas平台ftp下载文件到本地" + e.Message + JsonConvert.SerializeObject(e));
                        }
                    }
                    #endregion 
                }
                #endregion
                 
            }
            catch (Exception e)
            {
                Console.WriteLine("启动Ftp下载信息异常" + JsonConvert.SerializeObject(e));
            }
        } 
    }
}
